package com.yimidida.library.http;

import android.app.Activity;
import android.content.Context;

import com.lzy.okgo.model.Response;
import com.yimidida.library.base.LoadingDialog;
import com.yimidida.library.utils.ToastUtil;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Create on: 9/14/21
 * by Mr.Zhu
 * Description: 封装Loading
 */
public class LoadingBaseObserver implements Observer<Response<String>> {

    private boolean isShowLoading = false;
    private LoadingDialog loadingDialog;
    private Activity activity;

    public boolean isShowLoading() {
        return isShowLoading;
    }


    public void setShowLoading(Context activity) {
        this.activity = (Activity) activity;
        if (activity != null) {
            if (loadingDialog == null) {
                loadingDialog = new LoadingDialog((Activity) activity);
            }
            loadingDialog.showLoading();
        }
    }


    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(Response<String> stringResponse) {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        try {
//            String responseBody = stringResponse.body();
//            BaseResp bean = JsonSerializer.deSerialize(responseBody, BaseResp.class);
//            if (bean != null) {
//                if (stringResponse.code() == 401 && "SYS.0006".equals(bean.getErrorCode())) {
//                    UserLogical.getInstance().outLogin();
//                    ToastUtil.showLong("您的账号登录已失效，请重新登录");
//                    Intent intentLogin = new Intent(activity, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                    activity.startActivity(intentLogin);
//                    return;
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onError(Throwable e) {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        ToastUtil.showShort("请求失败");
    }

    @Override
    public void onComplete() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }
}
